import { Controller, Post, Body, UseGuards, Req, Inject, forwardRef, UseInterceptors } from '@nestjs/common'
import { UserService } from './user.service'
import { CreateUserDto, PhoneCreateUserDto } from './dto/create-user.dto'
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger'
import { TokenService } from '@/src/auth/token.service'
import { LoginUserDto } from './dto/login-user.dto'
import { ModifyUserDto } from './dto/update-user.dto'
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'
import { ModifyAvatarDto } from './dto/avatar.dto'
import { ModifyPassDto } from './dto/newPass.dto'
import { Request } from 'express'
import { VerifyEmailCodeDto, VerifyPhoneCodeDto } from './dto/verify-code.dto'
import { VerificationService } from '../verification/verification.service'
import { RateLimit } from '../common/rateLimit/rate-limit.decorator'
import { ForgotPassDto } from './dto/forgotPass.dto'
import { RedisService } from '../redis/redis.service'
@ApiTags('user')
@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly tokenService: TokenService,
    @Inject(forwardRef(() => VerificationService))
    private readonly verificationService: VerificationService,
    private readonly redisService: RedisService,
  ) { }

  // 注册用户
  @ApiOperation({ summary: '注册' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(3, 60 * 60 * 1000)
  @Post('register')
  async register(@Body() createUser: CreateUserDto) {
    await this.userService.register(createUser)
    return {
      isAdd: true
    }
  }

  // 手机注册
  @ApiOperation({ summary: '手机注册' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(3, 60 * 60 * 1000)
  @Post('phone/register')
  async registerByPhone(@Body() createUser: PhoneCreateUserDto) {
    await this.userService.registerByPhone(createUser)
    return {
      isAdd: true
    }
  }

  // 用户登录
  @ApiOperation({ summary: '登录' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(3, 60 * 1000)
  @Post('login')
  async login(@Body() data: LoginUserDto) {
    const temp = await this.userService.login(data)
    // 生成token
    const authInfo = await this.tokenService.generateToken(temp)

    // res.cookie('token', token, {
    //   httpOnly: true,
    //   secure: true,
    //   sameSite: 'lax',
    //   maxAge: 1000 * 60 * 60, // 1小时
    //   path: '/',
    //   domain: process.env.NODE_ENV === 'production' ? 'tears.asia' : 'localhost',
    // })
    return {
      id: temp.id,
      token: authInfo.token
    }
  }

  // 手机登录
  @ApiOperation({ summary: '手机快捷登录' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(3, 60 * 1000)
  @Post('phone/login')
  async loginByPhone(@Body() data: VerifyPhoneCodeDto) {
    const temp = await this.userService.loginByPhone(data)
    const authInfo = await this.tokenService.generateToken(temp)
    return {
      id: temp.id,
      token: authInfo.token
    }
  }

  // 退出登录
  @ApiOperation({ summary: '退出登录' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(3, 60 * 1000)
  @Post('logout')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async logout(@Req() req: Request) {
    const userId = req.user?.id as number
    await this.redisService.del(`token_${userId}`)
    return {
      isAdd: true,
    }
  }

  // 获取用户信息
  @ApiOperation({ summary: '用户信息' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(20, 60 * 1000)
  @Post('profile/info')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async getProfile(@Req() req: Request) {
    const user = await this.userService.getProfile(req.user?.id as number)
    return {
      account: user.account || user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      email: user.email,
      role: user.role
    }
  }

  // 修改用户信息
  @ApiOperation({ summary: '修改用户信息' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('profile/modify')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async modifyUser(@Body() data: ModifyUserDto, @Req() req: Request) {
    const userId = req.user?.id as number
    await this.userService.modifyUser(data, userId)
    return {
      isAdd: true,
    }
  }

  // 修改头像
  @ApiOperation({ summary: '更换头像' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('profile/avatar')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async modifyAvatar(@Body() data: ModifyAvatarDto, @Req() req: Request) {
    const userId = req.user?.id as number
    await this.userService.modifyAvatar(data, userId)
    return {
      isAdd: true,
    }
  }

  // 修改密码
  @ApiOperation({ summary: '修改密码' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('profile/changePass')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async modifyPass(@Body() data: ModifyPassDto, @Req() req: Request) {
    const userId = req.user?.id as number
    await this.userService.modifyPass(data, userId)
    return {
      isAdd: true,
    }
  }

  // 用户统计数据
  @ApiOperation({ summary: '用户统计数据' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(10, 60 * 1000)
  @Post('stat')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async getUserStat(@Req() req: Request) {
    const userId = req.user?.id as number
    return this.userService.getUserStat(userId)
  }

  // 每日签到
  @ApiOperation({ summary: '每日签到' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('checkin')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async checkin(@Req() req: Request) {
    const userId = req.user?.id as number
    await this.userService.checkin(userId)
    return {
      isAdd: true,
    }
  }

  // 获取用户当月签到统计信息
  @ApiOperation({ summary: '当月签到信息统计' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(20, 60 * 1000)
  @Post('checkin/stat')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async getMonthCheckinStat(@Req() req: Request) {
    const userId = req.user?.id as number
    return this.userService.getMonthCheckinStat(userId)
  }

  // 设置邮箱
  @ApiOperation({ summary: '修改用户邮箱' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('profile/updateEmail')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT')
  async updateEmail(@Body() data: VerifyEmailCodeDto, @Req() req: Request) {
    const userId = req.user?.id as number
    return this.userService.updateEmail(userId, data.email, data.code)
  }

  // 重置密码
  @ApiOperation({ summary: '重置密码' })
  @ApiConsumes('application/x-www-form-urlencoded')
  @RateLimit(5, 5 * 60 * 1000)
  @Post('profile/forgetPass')
  async resetPass(@Body() data: ForgotPassDto) {
    await this.userService.resetPassword(data)
    return {
      isAdd: true
    }
  }
}
